import { Injectable } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { Daily } from './daily.schema'
@Injectable()
export class DailyService {
  constructor(@InjectModel(Daily.name) private daily: Model<Daily>) {}
  async getDailyDate(req,res) {
    let data=await this.daily.find()
    res.send({
      code:200,
      data:data
    })
  }
  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
  getDateRange(days) {
    const today = new Date();
    const dates = [];
  
    for (let i = 0; i < days; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() - i);
      dates.push(this.formatDate(date));
    }
  
    return dates.reverse(); // 如果你希望日期从最早到最新排列，可以调用 reverse()
  }
  async searchDailyData(req,res){
    const {brand,partition,shop,platform,date,today}=req.body
    console.log(brand,partition,shop,platform,date,today)
    const dates=this.getDateRange(today)
    const arr=[{}]
    if(brand){
      arr.push({brand:brand})
    }
    if(partition){
      arr.push({partition:partition})
    }
    if(shop){
      arr.push({shop:shop})
    }
    if(platform){
      arr.push({platform:platform})
    }
    if(date){
      arr.push({date:date})
    }
    if(today){
      
      arr.push({date:{$in:dates}})
    }
    const data=await this.daily.find({$and:arr})
    
    console.log(data)
    res.send({
      code:200,
      data:data
    })
  }
  async addDailyData(body: any) {
    await this.daily.create(body)
    return {
      code: 200,
      message: '添加成功',
    }
  }
}
